<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Middleware\AuthMiddleware;
use App\Model\Menu;
use App\Model\RoleMenu;
use App\Model\User;
use App\Services\JwtTokenService;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller]
class AuthController extends AbstractController
{
    #[Inject]
    public JwtTokenService $jwtTokenService;

    #[PostMapping(path: '/auth/login')]
    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $source = $this->request->post('source');
        $user = User::query()->select('id', 'username', 'nickname', 'avatar','password')
            ->where('username', $username)
            ->where('source', $source)
            ->firstOrFail();
        if ($user->password != $password){
            return fail(201,'密码错误');
        }
        $token = $this->jwtTokenService->createToken($user->id, $source, time() + 3600 * 24, [], getClientIp());
        $user->token = $token;
        User::query()->where('id', $user->id)->update([
            'last_login_time' => date('Y-m-d H:i:s'),
            'ip' => getClientIp(),
            'ip_location' => getClientIp()
        ]);
        unset($user->password);
        return success($user);
    }

    #[Middlewares([AuthMiddleware::class])]
    #[GetMapping(path: '/auth/info')]
    public function info()
    {
        // var_dump(Context::get('uid'));
        $user = User::query()->select('id', 'username', 'nickname', 'avatar')->with(['roles'])->where('id', Context::get('uid'))->first();
        if ($user->id == 1) {
            $user->permissions = Menu::query()->get()->pluck('perm');
        } else {
            $roleId = $user->roles->pluck('id')->toArray();
            $menuId = RoleMenu::query()->whereIn('role_id', $roleId)->get()->pluck('menu_id')->toArray();
            $user->permissions = Menu::query()->whereIn('id', $menuId)->get()->pluck('perm');
        }

        $roles = $user->roles->pluck('code');
        unset($user->roles);
        $user->roles = $roles;
        return success($user);
    }

    #[Middlewares([AuthMiddleware::class])]
    #[PostMapping(path: '/auth/logout')]
    public function logout()
    {
        return success();
    }

}
